package com.juku2024.juku.dialog

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.juku2024.juku.R
import com.juku2024.juku.adapter.DialogEpisodeAdapter
import com.juku2024.juku.adapter.EpisodeGroupAdapter
import com.juku2024.juku.callback.OnEpisodeClickCallback
import com.juku2024.juku.model.EpisodeGroupModel
import com.juku2024.juku.model.EpisodesResponse
import com.juku2024.juku.tools.Constants
import com.juku2024.juku.tools.WrapGridLayoutManager
import com.juku2024.juku.tools.WrapLinearLayoutManager

class VideoEpisodeDialog(context: Context, style: Int = R.style.Down2UpDialogStyle): Dialog(context, style) {

    private lateinit var btnBack: View
    private lateinit var groupRecycler: RecyclerView
    private lateinit var episodeRecycler: RecyclerView

    // 当前的视频id，如果相同的视频，不再充值adapter
    private var currentVideoId = 0L
    // 展示dialog的时候，剧集列表显示的剧集数
    private var currentEpisodeIndex = 0

    private var isInit = false
    // 是否重置adapter
    private var isResetAdapter  = true

    // 当前视频分类
    private var category = Constants.VIDEO_CATEGORY_ALBUM
    private var episodeClick: OnEpisodeClickCallback? = null
    private var episodes: ArrayList<EpisodesResponse>? = null
    private val groupListAdapter by lazy { EpisodeGroupAdapter(ArrayList()) }
    private val episodeListAdapter by lazy { DialogEpisodeAdapter(ArrayList()) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window?.decorView?.setPadding(0, 0, 0, 0)
        val params = window?.attributes
        params?.width = ViewGroup.LayoutParams.MATCH_PARENT
        params?.height = ViewGroup.LayoutParams.MATCH_PARENT
        params?.gravity = Gravity.BOTTOM
        window?.attributes = params
        setContentView(R.layout.dialog_video_episode)
        btnBack = findViewById(R.id.dialog_source_btnBack)
        episodeRecycler = findViewById(R.id.dialog_source_episodeRecycler)
        episodeRecycler.setHasFixedSize(true)
        episodeRecycler.adapter = episodeListAdapter
        episodeListAdapter.setOnItemClickListener { _, _, position ->
            // 获取当前正在播放的剧集的position
            val currentPlayingItem = episodeListAdapter.getItem(position)
            if (currentPlayingItem.isPlaying) return@setOnItemClickListener

            val currentGroupModel = groupListAdapter.data.first { it.isSelected }

            val realPosition = currentGroupModel.start + position

            episodeClick?.onEpisodeClick(currentEpisodeIndex, realPosition, false)
            dismiss()
        }

        // 分组
        groupRecycler = findViewById(R.id.recycler_episodes)
        groupRecycler.setHasFixedSize(true)
        groupRecycler.layoutManager = WrapLinearLayoutManager(context, orientation = RecyclerView.HORIZONTAL)
        groupRecycler.adapter = groupListAdapter
        groupListAdapter.setOnItemClickListener { _, _, position ->
            val item = groupListAdapter.getItem(position)
            if (item.isSelected) return@setOnItemClickListener

            val oldIndex = groupListAdapter.data.indexOfFirst { it.isSelected }
            if (oldIndex >= 0) {
                groupListAdapter.getItem(oldIndex).isSelected = false
                groupListAdapter.notifyItemChanged(oldIndex)
            }

            item.isSelected = true
            groupListAdapter.notifyItemChanged(position)

            episodeListAdapter.setList(item.episodes)
        }

        btnBack.setOnClickListener {
            dismiss()
        }

        val topLayout = findViewById<View>(R.id.video_episode_tip)
        topLayout.setOnClickListener {
            dismiss()
        }

        isInit = true

        // 无需重置adapter
        if (!isResetAdapter) return

        setAdapter()
    }

    fun setEpisodes(videoId: Long, category: Int, episodesTemp: ArrayList<EpisodesResponse>?) {
        isResetAdapter = currentVideoId != videoId
        // 无需重置adapter
        if (!isResetAdapter) return
        this.category = category
        this.episodes = episodesTemp
        if (!isInit) return
        setAdapter()
    }

    fun setEpisodeClickCallback(episodeClick: OnEpisodeClickCallback?) {
        this.episodeClick = episodeClick
    }

    // 设置剧集列表的adapter
    private fun setAdapter() {
        episodeListAdapter.category = category
        val groupNum: Int
        when (category) {
            Constants.VIDEO_CATEGORY_ALBUM -> {
                groupNum = 50
                episodeRecycler.layoutManager = WrapGridLayoutManager(context, 5)
            }
            Constants.VIDEO_CATEGORY_VARIFY -> {
                groupNum = 20
                episodeRecycler.layoutManager = WrapGridLayoutManager(context, 2)
            }
            else -> {
                groupNum = 0
                episodeRecycler.layoutManager = WrapLinearLayoutManager(context)
            }
        }

        if (groupNum == 0) { // 电影
            groupRecycler.visibility = View.GONE
            episodeListAdapter.setList(episodes)
            return
        }

        currentEpisodeIndex = episodes?.indexOfFirst { it.isPlaying }?:0
        // 计算分组
        val groupDataList = groupEpisode(episodes, groupNum)
        groupListAdapter.setList(groupDataList)

        episodeListAdapter.setList(groupDataList.firstOrNull { it.isSelected }?.episodes)
    }

    private fun groupEpisode(source: ArrayList<EpisodesResponse>?, splitItemNum: Int): ArrayList<EpisodeGroupModel> {
        val groupListData = ArrayList<EpisodeGroupModel>()
        if (source == null || source.run { isEmpty()} || splitItemNum <= 0) return groupListData
        val currentIndex = source.indexOfFirst { it.isPlaying }
        if (source.size <= splitItemNum) {
            val groupModel = EpisodeGroupModel()
            // 源List元素数量小于等于目标分组数量
            groupModel.start = 0
            groupModel.end = source.size
            groupModel.episodes = source
            groupModel.isSelected = true
            groupListData.add(groupModel)
        } else {
            // 计算拆分后1ist数量
            val splitNum = if (source.size % splitItemNum == 0)
                source.size / splitItemNum
            else
                source.size / splitItemNum + 1

            for (i in 0 until splitNum) {
                val groupModel = EpisodeGroupModel()
                val start: Int
                val end: Int
                if (i < splitNum - 1) {
                    start = i * splitItemNum
                    end = (i + 1) * splitItemNum
                } else {
                    //最后一组
                    start = i * splitItemNum
                    end = source.size
                }
                groupModel.episodes = source.subList(start, end)
                groupModel.isSelected = currentIndex in start until end
                groupModel.start = start
                groupModel.end = end
                groupListData.add(groupModel)
            }
        }
        return groupListData
    }


    private fun <T> averageAssignFixLength(source: List <T>?, splitItemNum: Int): List<List<T>> {
        val result = ArrayList<List<T>>()
        if (source != null && source.run { isNotEmpty()} && splitItemNum > 0) {
            if (source.size <= splitItemNum) {
                // 源List元素数量小于等于目标分组数量
                result.add(source)
            } else {
                // 计算拆分后1ist数量
                val splitNum = if (source.size % splitItemNum == 0)
                    source.size / splitItemNum
                else
                    source.size / splitItemNum + 1

                var value: List<T>? = null
                for (i in 0 until splitNum) {
                    value = if (i < splitNum - 1) {
                        source.subList(i * splitItemNum, (i + 1) * splitItemNum)
                    } else {
                        //最后一组
                        source.subList(i * splitItemNum, source.size)
                    }
                    result.add(value)
                }
            }
        }
        return result
    }
}